package leetcode.tencent;

/**
 * @author Cheng Jun
 * Description: 给你一个正整数 n ，生成一个包含 1 到 n^2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 * @version 1.0
 * @date 2022/1/19 22:19
 * 典中典 面试题 二刷
 */
public class generateMatrix {

    public static void main(String[] args) {
        generateMatrix(3);
    }

    // 输入：n = 3
    // 输出：
    // [[1,2,3],
    //  [8,9,4],
    //  [7,6,5]]
    // 顺时针遍历矩阵
    static public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int num = 1;
        int top = 0;
        int right = n - 1;
        int bottom = n - 1;
        int left = 0;
        while (num <= n * n) {
            for (int i = left; i <= right && num <= n * n; i++) res[top][i] = num++;
            top++;
            for (int i = top; i <= bottom && num <= n * n; i++) res[i][right] = num++;
            right--;
            for (int i = right; i >= left && num <= n * n; i--) res[bottom][i] = num++;
            bottom--;
            for (int i = bottom; i >= top && num <= n * n; i--) res[i][left] = num++;
            left++;
        }
        return res;
    }
}
